<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\BaseException;
use App\Models\MemberBigData;
use App\Models\Order;
use App\Models\OrderLease;
use App\Models\OrderRadarXinyan;
use App\Models\OtherOrder;
use App\Models\RiskCredit;
use App\Services\CommonService;
use App\Services\ExportService;
use App\Services\OrderService;
use App\Services\RiskService;
use App\Services\XinyanService;
use Illuminate\Http\Request;

class XxfOrderController
{
    private $oneITime = 1; // 单位时间 一分钟
    private $oneIMax = 1; // 一个用户Ip一分钟最多仅允许访问访问10次

    private $platITime = 1; // 针对所有用户，单位时间内允许访问的最大次数
    private $platIMax = 1; // 针对所有的用户,该接口最多仅允许访问N次


    //担保大数据
    public function handle(Request  $request)
    {
        $redis = new \redis();
        $userid = $_SERVER['HTTP_USER_AGENT'];
        $redis->connect("127.0.0.1");
        $redis->select(0);
        //.... 针对平台全局锁，用于限制单位时间内所有用户访问的次数
        $platKey = md5($request->path());
        $platFlowCount = $redis->get($platKey);// 平台访问次数
        if($platFlowCount){
            if($platFlowCount >= $this->platIMax){
                throw new BaseException('平台超过限制');
            }
        }
        $redis->incr($platKey);// ++1 次访问次数
        !$platFlowCount && $redis->expire($platKey,$this->platITime); // 设置锁的有效时间

        $ip=$request->getClientIp();
        // ... 针对单个用户实现的访问锁
        $key = md5($ip.":".$userid);
        // 实现一个用户一分钟最多允许访问10次
        $userFlowCount = $redis->get($key); // 单个用户访问次数
        if($userFlowCount){
            if($userFlowCount >= $this->oneIMax){
                return [
                    'status'=>100,
                    'msg' =>"用户访问超过限制"
                ];
            }
        }
        $redis->incr($key);// ++1 次访问次数
        !$userFlowCount && $redis->expire($key,$this->oneITime);//设置锁的有效时间

        $request_data = $request->all();
        $verification_key= $request_data['verification_key'];

        $isCorrect = password_verify("worldlier_dlz", $verification_key);
        if(!$isCorrect){
            return [
                'status'=>100,
                'msg' =>"密钥有误"
            ];
        }

        $request['eight_before_order']=1;


        $data = Order::orderXxfList($request);
        $count = [];

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',['count'=>$count,'list'=>$data['list']]);
    }

    /**
     * 订单雷达风控大数据-布尔
     */

    public function getRadarData(Request $request){

        $input = $request->input();
        $verification_key= $input['verification_key'];
        $isCorrect = password_verify("worldlier_dlz", $verification_key);
        if(!$isCorrect){
            return [
                'status'=>100,
                'msg' =>"密钥有误"
            ];
        }


        if(!empty($input['orderId'])){

            $input = Order::from('sp_order_2 as o')->where('o.id',$input['orderId'])
                ->leftjoin('sp_member_2 as m','m.id','o.uid')
                ->select(
                    'o.id as orderId','o.uid','o.mobile as user_mobile','o.trade_no'
                    ,'m.cert_name','m.cert_no','m.mobile'
                )
                ->first();

            $risk_data = OrderRadarXinyan::getRiskData($input['orderId']);

            //有则输出，无则添加
            if($risk_data){

                $risk_data['data'] = json_decode($risk_data['result'])->data;

                $risk_data['risk_probe']=json_decode($risk_data['risk_probe_result']);


            }else{
//                $res=file_get_contents('https://api.doulaizuba.com/Supplier/Login/getRadarCount?member_id=1693377836');
//                $res=json_decode($res,true);
//                if($res['status']!=200){
//                    return ReturnMsg(CommonService::HTTP_CODE_FAIL,'雷达数据次数不足，请前往都来租宜人租商户中购买');
//                }

                //全景雷达
                $risk_data = XinyanService::fxTan($input);

                OrderRadarXinyan::setRiskData($input['orderId'],$risk_data,$input['cert_name'],$input['mobile'],$input['cert_no']);


                $risk_data['cert_name'] = $input['cert_name'];

                $risk_data['mobile'] = $input['mobile'];

                $risk_data['cert_no'] = $input['cert_no'];

                $risk_data['order_id'] = $input['orderId'];

                $risk_data['is_new_user'] = '1';

                $risk_data['start_at'] = date('Y-m-d H:i:s');

                $risk_data['end_at'] =  date('Y-m-d H:i:s',time()+7*24*60*60);



                $online_data = [];

                $online_data['user_type'] = OrderService::RISK_USER_TYPE_ADMIN; //管理员查看
                $online_data['member_id'] = '1693377836';

                OrderRadarXinyan::editRiskData($input['orderId'],$online_data);

            }

            $res = obToArray($risk_data);


            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$res);
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请选择要风控的订单');
        }

    }

    public function orderEightListExport(Request $request)
    {
        $input = $request->input();
        $verification_key = $input['verification_key'];
        $isCorrect = password_verify("worldlier_dlz", $verification_key);
        if (!$isCorrect) {
            return [
                'status' => 100,
                'msg' => "密钥有误"
            ];
        }

        $data = ExportService::orderXxfList($request);

        if(!$data){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'无数据');
        }

        return $data;

    }
    /**
     * 加密数据
     * @param array $data
     * @return array
     */
    public function encryptData(array $data = [], $is_encrypt = true)
    {
        if ($is_encrypt) {
            $data_str = json_encode($data);

            $key=substr(md5('dlzorder'), 8, 16);


            $encode = base64_encode(openssl_encrypt($data_str, "AES-128-ECB", $key, 1));
            return [
                'data' => $encode,
                'is_encrypt' => true //告诉前端，数据是否加密
            ];
        } else {
            return $data;
        }
    }

    public function decrypt($encryptedData) {
        $key=substr(md5('dlzorder'), 8, 16);
        $decrypted = openssl_decrypt(base64_decode($encryptedData), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }

    //接单平台发货
    public function otherDeliverOrder(Request $request){
        $request_data = $request->all();
        $member_id = $request_data['member_id'];
        $order_id = $request_data['other_data_id'];
        $data = [];
        if($member_id == '202405251855651266'){ //小马快租
            $data['status'] = true;
            $data['msg'] = '请求成功';
            OtherOrder::where('id',$order_id)->where('member_id',$member_id)->update(['success'=>1]);
        }else{
            $data['status'] = false;
            $data['msg'] = '请联系平台开通权限';
        }
        return $data;
    }

    //订单推送成功回调
    public function otherOrderSet(Request $request){
        $request_data = $request->all();
        $member_id = $request_data['member_id'];
        $order_id = $request_data['other_data_id'];
        $status = $request_data['status'];


        if(!$member_id||!$order_id){
            return [
                'status'=>100,
                'msg' =>"参数错误"
            ];
        }
        if($member_id != '202405251855651266') { //小马快租
            return [
                'status'=>100,
                'msg' =>"参数错误"
            ];
        }
       if($status&&$status==2){
            $res=OtherOrder::where('id',$order_id)->where('member_id',$member_id)->update(['status'=>2]);
        }else{
            $res=OtherOrder::where('id',$order_id)->where('member_id',$member_id)->update(['status'=>0]);
        }
        self::addLog('订单推送成功回调',$request_data,$res);
        if(!$res){
            return [
                'status'=>100,
                'msg' =>"无效other_data_id"
            ];
        }
        return [
            'status'=>200,
            'data'=>[],
            'msg' =>"success"
        ];
    }




    /**
     * 拾贝壳订单账单还款接口
     * 账单还款
     * 提前手动支付
     */
    public function submitLeasePay(Request $request){
        $request = $request->all();
        if($request['member_id']!='1720496753001'){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'fail');
        }
        $order = Order::from('sp_order_2 as o')->where('seller_id','1704471788')->where('username','beike')->where('o.old_order_id',$request['order_id'])
            ->select('o.id','o.flow_id','o.withhold_status','o.sign_no',)
            ->first();
        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        $OrderLease= OrderLease::where('which_period',$request['which_period'])->where('order_id',$order['id'])
            ->select(
                'id','which_period','rent','status'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }

        $successPayToOrderLease=OrderLease::where(['id'=>$OrderLease['id'],'order_id'=>$order['id']])
            ->update(['paid_rent'=>$OrderLease['rent'],
                'status'=>OrderLease::ORDER_LEASE_STATUS_PAID,
                'pay_time'=>time(),
                'pay_type'=>OrderLease::LEASE_PAY_TYPE_PREPAYMENT,
                'alipay_trade_no'=>$request['alipay_trade_no']
            ]);

        if(!$successPayToOrderLease){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
        }
        self::addLog('拾贝壳订单还款推送成功回调',$request,$OrderLease);

        //检测逾期订单状态
        $status = Order::checkOrderOverdueStatus($order['id']);
        if($status){
            Order::where(['id' => $order['id']])->update(['status'=>$status]);
        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交成功');
    }

    /**
     * 拾贝壳订单状态改变
     * 账单还款
     * 提前手动支付
     */
    public function submitOrderStatus(Request $request){
        $request = $request->all();
        if($request['member_id']!='1720496753001'){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'fail');
        }
        $order = Order::from('sp_order_2 as o')->where('seller_id','1704471788')->where('username','beike')->where('o.old_order_id',$request['order_id'])
            ->select('o.id','o.flow_id','o.withhold_status','o.sign_no',)
            ->first();
        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }

        if($request['status']==7){
            $order_status = 30;
        }else if($request['status']==6||$request['status']==10){
            $order_status = 60;
        }else if($request['status']==9){
            $order_status = 4;
        }else if($request['status']==0){
            $order_status = 1;
        }else if($request['status']==1){
            $order_status = 3;
        }else if($request['status']==4){
            $order_status = 10;
        }else if($request['status']==5){
            $order_status = 20;
        }else{
            $order_status=1;
        }

         self::addLog('拾贝壳订单状态更改',$request,['order_status'=>$order_status]);

        if($order_status){
            $data=[
                'status'=>$order_status,
            ];

            if($order_status==60&&isset($request['buyout_price'])&&$request['buyout_price']>0){
                $data['reduced_price']=$request['buyout_price'];
                $data['reduced_status']=1;
            }

            Order::where('id',$order['id'])->where('seller_id','1704471788')->update($data);
        }

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交成功');
    }
    public static function addLog($message,$request=[],$response=[]){
        $content = [
            'request'=>is_object($request) ? object_array($request) : $request,
            'response'=>is_object($response) ? object_array($response) : $response,
        ];
        \Illuminate\Support\Facades\Log::channel("customerinfo")->debug($message,$content);
    }

    //统计调用
    public function insertOrderCreditData(Request $request){
        $arr=['202409107012090001','202412041055210001'];//憨租租
        if(!in_array($request['member_id'],$arr)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'error');
        }
        $risk_data['user_name'] =$request['cert_name'];
        $risk_data['user_idcard'] = $request['cert_no'];
        $risk_data['user_mobile'] = $request['mobile'];
        $risk_data['verification_data'] = $request['result'];
        $risk_data['risk_report_url'] = $request['risk_report_url'];
        $risk_data['order_id'] = $request['order_id'];
        $risk_data['member_id'] = $request['member_id'];
        $risk_data['type'] = $request['type'];
        $risk_data['create_time'] = date('Y-m-d H:i:s',time());
       return RiskCredit::insert($risk_data);

    }


    //外部布尔调用
    public function outBooleData(Request $request)
    {
        $arr=['202409107012090001','202412041055210001'];//憨租租
        if(!in_array($request['member_id'],$arr)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'error');
        }
       $request=$request->all();
        $request['orderId'] = Order::from('sp_order_2 as o')
            ->where('m.cert_no',$request['cert_no'])
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->value('o.id');
     return   json_encode(RiskService::customRiskData($request));
    }

    //外部雷达调用
    public function outRadarData(Request $request)
    {
        $arr=['202409107012090001','202412041055210001'];//憨租租
        if(!in_array($request['member_id'],$arr)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'error');
        }
        $request=$request->all();
        $request['orderId'] = Order::from('sp_order_2 as o')
            ->where('m.cert_no',$request['cert_no'])
            ->leftjoin('sp_member_2 as m','m.id','o.uid')
            ->value('o.id');

        return  json_encode(RiskService::RadarData($request));
    }



}
